# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
import enhancedModel as em
import models.MPTemplates as MPTm
import shippingOrder as som
from datetime import timedelta

class MPModel( em.EnhancedModel ):
    __prefix__ = 'MilestonePlan'
    
    FIELD_SEPARATOR = ';;'
    DEFAULT_MP = -1
    # TODO: uzyc czegos lepszego niz delimetowany string

    plan = db.ListProperty(str)
    
    # Jaka to jest jednostka czasu? W mail.py przyjąłem, że godziny...
    currentDelay = db.IntegerProperty(default = 0)

    def showLink(self):
        return ("/mp/show1/id/%d" % self.ident)

    @staticmethod
    def tupleEncode(tuple):
        tuple[0] = som.SOModel.encodeTime(tuple[0])
        return (MPModel.FIELD_SEPARATOR.join(tuple))

    @staticmethod
    def tupleDecode(str):
        tuple = (str.split(MPModel.FIELD_SEPARATOR))
        tuple[0] = som.SOModel.decodeTime(tuple[0])
        return tuple

    @staticmethod
    def createFromTemplate(template, startTime):
        new = MPModel ()
        for i, point in enumerate(template['points']):
            time = timedelta(hours=int(point['timeDelta'])) + startTime
            template['points'][i] = MPModel.tupleEncode([time, point['city'], point['status']])
        new.plan = template['points']
        new.put()
        return new.ident

    @staticmethod
    def getTemplates():
        #templatesFile = open('./MPTemplates.txt', 'r')
        #templates = templatesFile.read().split('\n\n')
        templates = MPTm.MPTemplateModel.file().split('\n\n')
        #templates.pop()
        for i, template in enumerate(templates):
            template = template.split('\n')
            tpl = {}
            tpl['origin'], tpl['destination'], tpl['type'] = template.pop(0).split(',')

            for j, point in enumerate(template):
                pointInfo = {}
                pointInfo['timeDelta'], pointInfo['city'], pointInfo['status'] = point.split(',')
                template[j] = pointInfo
            tpl['points'] = template
            templates[i] = tpl

        return templates

    @staticmethod
    def getCities():
        cities = []
        #citiesFile = open('./MPCities.txt', 'r')
        #cities = citiesFile.read().split('\n')
        #for i, city in enumerate(cities):
         #   cityInfo = {}
           # cityInfo['city'], cityInfo['fullCity'] = city.split(',')
          #  cities[i] = cityInfo
            
        return cities

    @staticmethod
    def findTemplate(origin, destination):

        templates = MPModel.getTemplates()

        for template in templates:
            if template['origin'] == origin and template['destination'] == destination:
                return template

        return {}

    @staticmethod
    def showLink(ident):
        return ("/mp/show1/id/%d" % ident)

    @staticmethod
    def linkTo(ident):
        if ident == MPModel.DEFAULT_MP:
            return 'none'
        else:
            return ("<a href='%s'>%s</a>" % (MPModel.showLink(ident),ident))

